import os
import datetime
import logging
import logging.config
from src.database import AlchemyDB
import asyncio
import src.config as config
import atexit
import time
from typing import Union
from fastapi import FastAPI
from uuid import UUID


# Инициализация глобальных переменных
db = AlchemyDB(alchemy_url=config.DB_ALCHEMY)
logging.config.dictConfig(config.LOGGING_SETUP)
logging.basicConfig(format=u'[%(asctime)s][%(levelname)s] ::: %(filename)s(%(lineno)d) -> %(message)s',
                    level="INFO", filename='logs/all.log')
logger = logging.getLogger('logger')

tags_metadata = [
    {
        "name": "users",
        "description": "Operations with users.",
    },
    {
        "name": "bookings",
        "description": "Operations with bookings.",
    },
]
app = FastAPI(openapi_tags=tags_metadata)


# @app.get("/")
# async def read_root():
#     return {"Hello": "World"}
#
#
# @app.get("/items/{item_id}")
# async def read_item(item_id: int, q: Union[str, None] = None):
#     return {"item_id": item_id, "q": q}


async def main():
    logger.info("App online.")
    config.START_TIME = time.time()
    await db.connect()
    # TESTS
    # print(await db.get_users())
    # print(await db.get_user(user_id='880e5a06-372c-45f1-8cd6-7eac52c2b6b7'))
    # print(await db.get_user(user_id=UUID('880e5c06-372c-45f1-8cd6-7eac52c2b6b7')))


@atexit.register
def at_exit():
    if config.START_TIME == 0:
        return None
    dt = datetime.datetime.fromtimestamp(time.time()) - datetime.datetime.fromtimestamp(config.START_TIME)
    logger.info(f"App offline. Online time: {dt}")


if __name__ == "__main__":
    for log_file in ('all.log', 'err.log'):
        with open(f'logs/{log_file}', 'a') as log:
            log.write(f'=============================\n'
                      f'New app session\n'
                      f'[{datetime.datetime.now()}]\n'
                      f'=============================\n')
    asyncio.run(main())
    os.system(f"uvicorn src.main:app --host {config.SERVER_ADDR} --port {config.SERVER_PORT}")
